package com.ruoyi.resume.service.impl;

import com.ruoyi.resume.domain.model.Category;
import com.ruoyi.resume.domain.model.ResumeTag;
import com.ruoyi.resume.domain.model.SplitResumeResult;
import com.ruoyi.resume.domain.request.LabelingRequest;
import com.ruoyi.resume.mapper.CategoryMapper;
import com.ruoyi.resume.mapper.ResumeTagMapper;
import com.ruoyi.resume.service.FirstLabelingService;
import com.ruoyi.resume.service.ResumeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.ResponseEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

@Service
public class FirstLabelingServiceImpl implements FirstLabelingService {

    private static final Logger logger = LoggerFactory.getLogger(FirstLabelingServiceImpl.class);

    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private ResumeTagMapper resumeTagMapper;
    @Autowired
    private ResumeService resumeService;

    @Override
    public List<Map<String, Integer>> firstLabeling(SplitResumeResult splitResumeResult) {
        Integer resumeId = splitResumeResult.getBasicInfo().getId();
        if (resumeId == null || splitResumeResult == null) {
            logger.error("firstLabeling: resumeId 或 splitResumeResult 为空");
            throw new IllegalArgumentException("resumeId 或 splitResumeResult 不能为空");
        }

        // 提取所有 Category 数据
        List<Category> categories = categoryMapper.selectAllCategories();
        if (categories.isEmpty()) {
            logger.warn("Category 表中没有数据");
            return Collections.emptyList();
        }

        List<Map<String, Integer>> allProcessedLabels = new ArrayList<>();
        RestTemplate restTemplate = new RestTemplate();

        for (Category category : categories) {
            String algorithmUrl = category.getAlgorithmIdentifier();

            // 检查算法地址是否存在
            if (algorithmUrl != null && !algorithmUrl.isEmpty()) {
                logger.info("检测到 Category ID={} 的算法地址: {}", category.getId(), algorithmUrl);

                try {
                    // 创建请求对象并设置参数
                    LabelingRequest request = new LabelingRequest();
                    request.setSplitResumeResult(splitResumeResult); // 填充 SplitResumeResult
                    request.setCategory(category); // 填充 Category

                    // 调用算法接口
                    ResponseEntity<List> response = restTemplate.postForEntity(algorithmUrl, request, List.class);
                    if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
                        List<Map<String, Integer>> labels = response.getBody();
                        logger.info("算法返回的标签：{}", labels);

                        // 插入标签到数据库
                        insertLabelsToDatabase(resumeId, labels);

                        // 收集处理过的标签
                        allProcessedLabels.addAll(labels);
                    } else {
                        logger.warn("调用算法接口返回非 2xx 响应: {}", response.getStatusCode());
                    }
                } catch (Exception e) {
                    logger.error("调用算法接口失败: {}", algorithmUrl, e);
                }
            } else {
                logger.info("Category ID={} 没有算法地址，跳过", category.getId());
            }
        }

        return allProcessedLabels;
    }

    private void insertLabelsToDatabase(Integer resumeId, List<Map<String, Integer>> labels) {
        if (labels.isEmpty()) {
            logger.warn("insertLabelsToDatabase: labels 为空，跳过插入操作");
            return;
        }

        for (Map<String, Integer> label : labels) {
            for (Map.Entry<String, Integer> entry : label.entrySet()) {
                String tagValue = entry.getKey();
                Integer tagId = entry.getValue();

                ResumeTag resumeTag = new ResumeTag();
                resumeTag.setResumeId(resumeId);
                resumeTag.setTagId(tagId);
                resumeTag.setTagValue(tagValue);

                try {
                    // 检查是否已存在
                    int count = resumeTagMapper.countResumeTag(resumeId, tagId);
                    if (count == 0) {
                        resumeTagMapper.insertResumeTag(resumeTag);
                        logger.info("插入标签：resumeId={}, tagId={}, tagValue={}", resumeId, tagId, tagValue);
                    } else {
                        logger.warn("标签已存在：resumeId={}, tagId={}", resumeId, tagId);
                    }
                } catch (Exception e) {
                    logger.error("插入标签到数据库失败：resumeId={}, tagId={}, tagValue={}", resumeId, tagId, tagValue, e);
                }
            }
        }
    }

    public List<Map<String, Integer>> generateLabelsForResume(Integer resumeId){
        SplitResumeResult splitResumeResultList = resumeService.getResumeContentById(resumeId);
        List<Map<String,Integer>> labels = firstLabeling(splitResumeResultList);
        return labels;
    }
}
